package com.itany.controller;

import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.HashMap;
import java.util.Map;

/**
 * websocket请求处理类
 */
public class SpringWebSocketHandler extends TextWebSocketHandler {


    public static Map<String, WebSocketSession> users
            = new HashMap<String, WebSocketSession>();

    public static String USER_ID="WEBSOCKET_USERID";

    /**
     * 连接成功时触发等价于onopen
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("-------------onopen-----------------");
        String userId=(String)session.getAttributes().get(SpringWebSocketHandler.USER_ID);
         users.put(userId,session);
    }

    /**
     * 关闭连接时触发登记于onclose
     * @param session
     * @param status
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        String userId=(String)session.getAttributes().get(SpringWebSocketHandler.USER_ID);
        if(session.isOpen()){
            session.close();
        }
        users.remove(userId);
    }

    /**
     * 发生异常时触发等价于onerror
     * @param session
     * @param exception
     * @throws Exception
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        String userId=(String)session.getAttributes().get(SpringWebSocketHandler.USER_ID);
        if(session.isOpen()){
            session.close();
        }
        users.remove(userId);
    }


    /**
     * 接收客户端信息时触发等价于onmessage
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String userId=(String)session.getAttributes().get(SpringWebSocketHandler.USER_ID);
        for (String id:users.keySet()){
            if(users.get(id)!=null && users.get(id).isOpen()){
                  users.get(id).sendMessage(new TextMessage(userId+":"+message.getPayload()));
            }
        }
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
